import { Controller, Post, BodyParam, Param, UploadedFile, Get } from 'routing-controllers';
import { FileService } from '../service/file.service';
import { Code, CodeMessage } from '../utils/code';
import { Result } from '../utils/result';

import { Service, Inject } from 'typedi';
import multer from '@koa/multer';

@Service()
@Controller('/file')
export class FileController {
  @Inject()
  fileService: FileService;

  @Post('/upload')
  async upload(@BodyParam('uid') uid: string, @UploadedFile('file') file: multer.File) {
    console.log(file);
    const isUploaded = await this.fileService.uploadFile(uid, file);
    if (isUploaded) {
      return Result.ok(Code.SUCCESS, '上传文件成功');
    }
    return Result.fail(Code.ERROR_FILE_UPLOAD, CodeMessage[Code.ERROR_FILE_UPLOAD]);
  }

  @Get('/download/:filename')
  async download(@Param('filename') filename: string) {
    const file = await this.fileService.downloadFile(filename);
    if (file) return file;
    return Result.fail(Code.ERROR_FILE_DOWNLOAD, CodeMessage[Code.ERROR_FILE_DOWNLOAD]);
  }
}
